package org.lq.service.impl;

import org.lq.dao.CommentRepository;
import org.lq.entity.Comment;
import org.lq.service.CommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentRepository commentRepository;

    @Override
    public List<Comment> listCommentByBlogId(Long blogId) {
        Sort sort = new Sort("createTime");
        List<Comment> comments = commentRepository.findByBlogIdAndParentCommentNull(blogId, sort);
        return eachComment(comments);
    }
    @Override
    @Transactional
    public Comment saveComment(Comment comment) {
        Long parentCommentId = comment.getParentComment().getId();
        System.out.println("parentCommentId是---------------"+parentCommentId);
        if(parentCommentId != -1){
            comment.setParentComment(commentRepository.findOne(parentCommentId));
        }else{
            comment.setParentComment(null);
        }
        comment.setCreateTime(new Date());
        return commentRepository.save(comment);
    }
    /**
     * 循环每个顶级评论节点
     */
    private List<Comment> eachComment(List<Comment> comments){
        ArrayList<Comment> commentsView = new ArrayList<Comment>();
        for(Comment comment : comments){
            Comment c = new Comment();
            BeanUtils.copyProperties(comment,c);
            commentsView.add(c);
        }
        //合并评论的各层集合到第一级子集合中
        combinChildren(commentsView);
        return  commentsView;
    }

    /**
     *
     * @param comments root 根节点 blog不为空的对象集合
     */
   private  void combinChildren(List<Comment> comments){
        for(Comment comment : comments){
            List<Comment> reply1 = comment.getReplyComments();
            for(Comment reply : reply1){
                //循环迭代，找出子代，存放在tempReply中
                recursively(reply);
            }
            //修改顶级节点的reply集合为迭代处理集合
            comment.setReplyComments(tempRelys);
            //清除临时存放区
            tempRelys = new ArrayList<>();
        }
   }

    // 存放跌点找出所有子集的集合
    private List<Comment> tempRelys = new ArrayList<>();
   private  void recursively(Comment comment){
       tempRelys.add(comment);//顶节点添加到临时存放集合中
       if(comment.getReplyComments().size()>0){
           List<Comment> replyss = comment.getReplyComments();
           for(Comment reply:replyss){
               tempRelys.add(reply);
               if(reply.getReplyComments().size()>0){
                   recursively(reply);
               }
           }
       }
   }

}
